package com.baidu.day05;

import java.util.ArrayList;

public class UserService {
    static ArrayList<User> userList = new ArrayList<>();
    //初始化用户
    static {
        userList.add(new User(1, "admin", "admin", 0.0));
        userList.add(new User(2, "test1", "test1", 100.0));
    }
    // 注册
    public boolean register(User user) {
        for (User u : userList) {
           if (u.getAccount().equals(user.getAccount())) {
              System.out.println("该用户已存在");
              return false;
           }
        }
        return userList.add(user);
    }

    // 登录
    public User login(String account, String password) {
        for (User u : userList) {
            if (u.getAccount().equals(account) && u.getPassword().equals(password)) {
                return u;
            }
        }
        return null;
    }

    // 查找
    public void findAll() {
        for (User u : userList) {
            System.out.println("用户账号:" + u.getAccount() + "\t\t" + "用户余额:" + u.getBalance());
        }
    }

    //购买
    public void buy(String goodsName,int goodsNum) {
        //获取所有商品
        ArrayList<Goods> goodsList = GoodsService.goodsList;
        for (int i = 0; i < goodsList.size(); i++) {
            //进行购买
            if(goodsList.get(i).getName().equals(goodsName)) {
                Goods goods = goodsList.get(i);
                if(goods.getStock() < goodsNum) {
                    System.out.println("库存不足");
                    return;
                }else {
                    goods.setStock(goods.getStock() - goodsNum);
                    System.out.println("购买成功");
                }
            }
        }

    }
}
